package exilim.exf1.cspacker.util;

import java.awt.Component;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JFileChooser;

/**
 * 
 * @author Janos
 * @version 14.08.2010 | 18:05:14
 * 
 */
public class FileUtil {

	/* THREAD-SAFE SINGLETON */
	private static class SINGLETON {
		static final FileUtil SINGLETON = new FileUtil();
	}

	public static FileUtil getInstance() {
		return SINGLETON.SINGLETON;
	}

	private FileUtil() {
	}

	/* ********************* */

	private static final String FILE_EXT_REGEX = "(.*?)(\\.[^\\.]*)?"; //$NON-NLS-1$
	private static final Pattern FILE_EXT_PATTERN = Pattern.compile(FILE_EXT_REGEX);

	/**
	 * Returns the name of the file without it's file extension.
	 */
	public String getName(final File f) {
		if (f == null) {
			return null;
		}

		final Matcher matcher = FILE_EXT_PATTERN.matcher(f.getName());
		if (!matcher.matches()) {
			// cant't happen!
			return null;
		}
		return matcher.group(1);
	}

	public static File promtForDirectory() {
		return promtForDirectory(null, null, null);
	}

	public static File promtForDirectory(final File currentDirectory, final Component parent, final String dialogTitle) {

		final JFileChooser fileChooser = new JFileChooser();
		if (dialogTitle != null) {
			fileChooser.setDialogTitle(dialogTitle);
		}
		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		fileChooser.setMultiSelectionEnabled(false);

		if (currentDirectory == null || !currentDirectory.exists()) {
			File dir = fileChooser.getFileSystemView().getHomeDirectory();
			dir = fileChooser.getFileSystemView().getFiles(dir, true)[0];
			fileChooser.setCurrentDirectory(dir);
		} else {
			fileChooser.setCurrentDirectory(currentDirectory);
		}

		final int result = fileChooser.showOpenDialog(parent);

		if (result == JFileChooser.CANCEL_OPTION) {
			return null;
		}

		final File selectedFile = fileChooser.getSelectedFile();
		return selectedFile;
	}

}
